package com.ls.x.activity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

import com.ls.x.R;
import com.ls.x.activity.beans.AlertModelBean;
import com.ls.x.adapter.AlertModelListViewAdapter;
import com.ls.x.tool.DatabaseHelper;
import com.ls.x.tool.Debug;

public class ContentEditActivity extends TabActivity {

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {
		super.finish();
		// if (bitmap != null) {
		// if (!bitmap.isRecycled()) {
		// bitmap.recycle();
		// }
		// }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ActivityGroup#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
	}

	private static final int INTENT_REQUEST_CODE_FOR_START_CAMERA_ACTRIVTY = 0;
	public static final int INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_CREATE_ACTION = 1;
	public static final int INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_EDIT_ACTION = 2;

	private TabHost tabHost = null;
	private final int DIALOG_SELECT_PICTURE = 0;
	private final int DIALOG_CUSTOM_INCIDENT_CLASS = 1;
	private final int DIALOG_CUSTOM_INCIDENT_REPEAT_TYPE = 2;
	private final int DIALOG_REMIND_MODEL_LIST_ACTION = 3;
	private ListView alertModelListView = null;
	private EditText edtTitle = null;
	private EditText edtSummary = null;
	private Spinner spinnerLevel = null;
	private Button buttonStartDate = null;
	private Spinner spinnerRepeatType = null;
	private Button addAlertModelButton = null;
	private Spinner spinnerClass = null;
	private Date startDate = null;
	private int year;
	private int month;
	private int day;
	private int hour;
	private int minute;
	private Button choosePictureButton;
	private Button recordVoiceButton;
	private Button buttonSave = null;
	private Button buttonCancel = null;
	private CheckBox checkBoxShareToGroup = null;
	private Spinner shareToSpinner = null;
	private ArrayAdapter<CharSequence> shartToSpinnerAdapter = null;
	private CheckBox checkBoxShareTask = null;
	private CheckBox checkBoxShareBySMS = null;
	private CheckBox checkBoxShareByEmail = null;
	private long context_id = 0;
	private boolean isNewContext = true;
	private DatabaseHelper dbHelper = null;
	private SQLiteDatabase db = null;
	private Cursor cursor = null;
	private Builder builder = null;
	private Bitmap bitmap;
	private Map<Integer, ArrayList<View>> imageShowMap;
	private String[] dialogitems;

	private String image_note = "";
	private EditText edt_imageNote;
	private LinearLayout imageListLayout;
	private String lastImageFileName;
	private String imageFileDirPath;
	private String image_path;
	private Map<Integer, ArrayList<String>> imageDataMap;
	private Map<Integer, ArrayList<String>> imageNewDataMap;
	private Map<Integer, String> imageDeleteDataMap;
	private ImageView iv_image;
	private TextView tv_image_note;
	private ArrayList<String> imageDataList;
	private int imageId;
	private AlertModelListViewAdapter alertModelListViewArrayAdapter;
	private Bundle bundleForDialog = null;
	private AlertDialog alertDialog = null;
	private Dialog dialog = null;
	private int imageOriginalCount;

	// TODO
	private TableLayout voiceListLayout;
	private EditText edt_voiceNote;
	private ImageView iv_voice;
	private TextView tv_voice_note;
	private int voiceId;
	private String voice_note = "";
	private String voiceDirPath;
	private String lastVoiceFilesName;
	private String voice_path;
	// private Map<Integer, ArrayList<View>> voiceShowMap;
	private Map<Integer, View> voiceShowMap;
	private Map<Integer, ArrayList<String>> voiceNewDataMap;
	private Map<Integer, ArrayList<String>> voiceDataMap;
	private Map<Integer, String> voiceDeleteDataMap;
	private Button btn_play_pause;
	private Button btn_stop;
	private Button btn_record;
	private ProgressBar psb_record;
	private TextView tv_record_time;
	private File soundFile;
	private MediaRecorder mRecorder;
	private MediaPlayer mPlayer;
	private boolean isRecordButtonPressed = false;
	private boolean isPlayButtonPressed = false;
	private View voiceDialogView;
	private boolean isFirstTimeOfAddVoice = true;
	private TableRow voiceListLayoutRow;
	private ArrayList<String> voiceDataList;
	private SetRecordTimeThread recordTimeThread;
	private int voiceOriginalCount;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		dbHelper = DatabaseHelper.getDBhelper(ContentEditActivity.this);
		db = dbHelper.getReadableDatabase();
		setContentView(R.layout.page_edit_content);
		getContextIdFromIntent();
		initializeViewInLayout();
		if (!isNewContext) {
			fillContextEditor(context_id);
		}
	}

	private void initializeImageVariables() {
		if (isNewContext) {
			if (imageShowMap == null) {
				imageShowMap = new HashMap<Integer, ArrayList<View>>();
			}
			if (imageNewDataMap == null) {
				imageNewDataMap = new HashMap<Integer, ArrayList<String>>();
			}
		} else {
			if (imageShowMap == null) {
				imageShowMap = new HashMap<Integer, ArrayList<View>>();
			}
			if (imageDataMap == null) {
				imageDataMap = new HashMap<Integer, ArrayList<String>>();
			}
			if (imageNewDataMap == null) {
				imageNewDataMap = new HashMap<Integer, ArrayList<String>>();
			}
			if (imageDeleteDataMap == null) {
				imageDeleteDataMap = new HashMap<Integer, String>();
			}
		}
	}

	private void initializeVoiceVariables() {
		if (isNewContext) {
			if (voiceShowMap == null) {
				voiceShowMap = new HashMap<Integer, View>();
			}
			if (voiceNewDataMap == null) {
				voiceNewDataMap = new HashMap<Integer, ArrayList<String>>();
			}
		} else {
			if (voiceShowMap == null) {
				voiceShowMap = new HashMap<Integer, View>();
			}
			if (voiceDataMap == null) {
				voiceDataMap = new HashMap<Integer, ArrayList<String>>();
			}
			if (voiceNewDataMap == null) {
				voiceNewDataMap = new HashMap<Integer, ArrayList<String>>();
			}
			if (voiceDeleteDataMap == null) {
				voiceDeleteDataMap = new HashMap<Integer, String>();
			}
		}
	}

	private void getContextIdFromIntent() {
		Intent intent = getIntent();
		if (intent.hasExtra("context_id")) {
			isNewContext = false;
			context_id = intent.getExtras().getLong("context_id");
		} else {
			isNewContext = true;
			context_id = (new Date()).getTime();
		}
	}

	// 获得Layout文件中的各种组件
	private void initializeViewInLayout() {
		tabHost = this.getTabHost();

		// 创建“内容”选项卡
		tabHost.addTab(tabHost.newTabSpec("content_tab").setIndicator("内容")
				.setContent(R.id.tabContentLinearLayout));
		// 创建“提醒”选项卡
		tabHost.addTab(tabHost.newTabSpec("remind_tab").setIndicator("提醒")
				.setContent(R.id.tabRemindLinearLayout));
		// 创建“分享”选项卡
		tabHost.addTab(tabHost.newTabSpec("share_tab").setIndicator("分享")
				.setContent(R.id.tabShareLinearLayout));
		// 设置当前选中的tab标签
		tabHost.setCurrentTabByTag("content_tab");

		// 标签-空 为了避免文本框获取节点

		// 文本输入框-标题组件
		edtTitle = (EditText) findViewById(R.id.titleEditText);
		// 文本输入框-摘要组件
		edtSummary = (EditText) findViewById(R.id.summaryEditText);

		// 按钮-“添加图片”
		choosePictureButton = (Button) tabHost
				.findViewById(R.id.btn_edit_page_add_picture);
		choosePictureButton.setOnClickListener(new CameraButtonClickListener());
		imageFileDirPath = Environment.getExternalStorageDirectory()
				+ "/.xProject/images/" + context_id + "/";
		// 按钮-“添加录音”
		recordVoiceButton = (Button) tabHost
				.findViewById(R.id.btn_edit_page_add_voice);
		recordVoiceButton.setOnClickListener(new VoiceButtonClickListener());
		voiceDirPath = Environment.getExternalStorageDirectory()
				+ "/.xProject/voice/" + context_id + "/";
		voiceListLayout = (TableLayout) findViewById(R.id.tblayout_edit_page_voice_list);

		// 下拉框-级别
		spinnerLevel = (Spinner) findViewById(R.id.spinnerContentLevel);
		ArrayAdapter<CharSequence> spinnerLevelAdapter = ArrayAdapter
				.createFromResource(this,
						R.array.spinner_edit_page_content_level,
						android.R.layout.simple_spinner_item);
		spinnerLevelAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerLevel.setAdapter(spinnerLevelAdapter);

		// 按钮-开始时间
		buttonStartDate = (Button) findViewById(R.id.button_start_date);
		buttonStartDate.setOnClickListener(new DateTimeBtnListener());

		// 下拉框-重复模式
		spinnerRepeatType = (Spinner) findViewById(R.id.repeatTypeSpinner);
		ArrayAdapter<CharSequence> repeatTypeSpinnerAdapter = ArrayAdapter
				.createFromResource(this,
						R.array.spinner_edit_page_remind_frequency,
						android.R.layout.simple_spinner_item);
		repeatTypeSpinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerRepeatType.setAdapter(repeatTypeSpinnerAdapter);

		// 下拉框-类别
		spinnerClass = (Spinner) findViewById(R.id.classSpinner);
		ArrayAdapter<CharSequence> classSpinnerAdapter = ArrayAdapter
				.createFromResource(this, R.array.spinner_edit_page_class,
						android.R.layout.simple_spinner_item);
		classSpinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerClass.setAdapter(classSpinnerAdapter);

		// 列表-提醒模式
		alertModelListView = (ListView) findViewById(R.id.alertModelListView);
		alertModelListViewArrayAdapter = new AlertModelListViewAdapter(this,
				android.R.layout.simple_list_item_single_choice);
		alertModelListView.setAdapter(alertModelListViewArrayAdapter);
		// reSetListViewHeight(alertModelListView);//
		// 修正由于ScrollView和ListView嵌套造成的ListView高度问题

		alertModelListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						AlertModelBean alertModelBean = (AlertModelBean) alertModelListViewArrayAdapter
								.getItem(position);

						Bundle bundle = new Bundle();
						bundle.putString("id", alertModelBean.getId() + "");
						bundle.putString("name", alertModelBean.getName() + "");
						bundle.putString("mode", alertModelBean.getMode() + "");
						bundle.putString("remindTimes",
								alertModelBean.getRemindTimes() + "");
						bundle.putString("smsNumber",
								alertModelBean.getSmsNumber() + "");
						bundle.putString("alertContent",
								alertModelBean.getAlertContent() + "");

						bundleForDialog = bundle;

						showDialog(DIALOG_REMIND_MODEL_LIST_ACTION);

						return true;
					}
				});

		// 按钮-新建提醒模式
		addAlertModelButton = (Button) findViewById(R.id.addAlertModelButton);
		addAlertModelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ContentEditActivity.this,
						AlertEditActivity.class);
				ContentEditActivity.this
						.startActivityForResult(intent,
								INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_CREATE_ACTION);
			}
		});

		checkBoxShareToGroup = (CheckBox) findViewById(R.id.checkBoxShareToGroup);
		checkBoxShareToGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (!isChecked) {
							shartToSpinnerAdapter = ArrayAdapter
									.createFromResource(
											ContentEditActivity.this,
											R.array.spinner_share_to_user,
											android.R.layout.simple_spinner_item);
						} else {
							shartToSpinnerAdapter = ArrayAdapter
									.createFromResource(
											ContentEditActivity.this,
											R.array.spinner_share_to_group,
											android.R.layout.simple_spinner_item);
						}
						shartToSpinnerAdapter
								.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						shareToSpinner.setAdapter(shartToSpinnerAdapter);

					}
				});

		// 按钮-"分享给"
		shareToSpinner = (Spinner) findViewById(R.id.spinnerShareTo);
		shartToSpinnerAdapter = ArrayAdapter.createFromResource(this,
				R.array.spinner_share_to_user,
				android.R.layout.simple_spinner_item);
		shartToSpinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		shareToSpinner.setAdapter(shartToSpinnerAdapter);

		checkBoxShareTask = (CheckBox) findViewById(R.id.checkBoxShareTask);
		checkBoxShareBySMS = (CheckBox) findViewById(R.id.checkBoxShareBySMS);
		checkBoxShareByEmail = (CheckBox) findViewById(R.id.checkBoxShareByEmail);

		// 共同用一个保存按钮
		buttonSave = (Button) findViewById(R.id.button_save_edit_context);
		buttonSave.setOnClickListener(new SaveButtonOnClickListener());

		// 取消按钮
		buttonCancel = (Button) findViewById(R.id.button_cancel_edit_context_page);
		buttonCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onDestroy();
				finish();
			}
		});

	}

	public void fillContextEditor(long id) {
		// 选择编辑条目是，通过该方法填充相应的控件
		// 填充文本及选项
		cursor = db.rawQuery("select * from context where id = " + id, null);

		if (cursor.moveToNext()) {
			// 标题框
			edtTitle.setText(cursor.getString(cursor.getColumnIndex("title")));
			// 摘要框
			edtSummary.setText(cursor.getString(cursor
					.getColumnIndex("summary")));
			// 级别
			int levelPosition = getSpinnerPosition(
					cursor.getString(cursor.getColumnIndex("level")),
					R.array.spinner_edit_page_content_level);
			spinnerLevel.setSelection(levelPosition);

			// 开始时间
			startDate = new Date(Long.parseLong(cursor.getString(cursor
					.getColumnIndex("start_date"))));
			buttonStartDate.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm")
					.format(startDate));

			// 重复
			int repeatPosition = getSpinnerPosition(
					cursor.getString(cursor.getColumnIndex("repeat")),
					R.array.spinner_edit_page_remind_frequency);
			spinnerRepeatType.setSelection(repeatPosition);

			// 类别
			int classPosition = getSpinnerPosition(
					cursor.getString(cursor.getColumnIndex("class")),
					R.array.spinner_edit_page_class);
			spinnerClass.setSelection(classPosition);

			// remind_model
			String remindModelIdStr = cursor.getString(cursor
					.getColumnIndex("mode"));
			if (remindModelIdStr != null && !remindModelIdStr.equals("")) {
				int remindModelId = Integer.parseInt(remindModelIdStr);
				int position = 0;
				if (remindModelId != 0) {
					position = alertModelListViewArrayAdapter
							.getPositionByRemindModelId(remindModelId);
				}

				alertModelListView.setItemChecked(position, true);
			}

		}

		// 从数据库读取图片数据
		initializeImageVariables();
		cursor = db.rawQuery("select * from image where context_id = " + id,
				null);
		while (cursor.moveToNext()) {
			image_path = cursor.getString(cursor.getColumnIndex("image_path"));
			image_note = cursor.getString(cursor.getColumnIndex("image_note"));
			setImageView();
			setImageData();
		}

		// 从数据库读取录音数据
		// TODO
		initializeVoiceVariables();
		cursor = db.rawQuery("select * from voice where context_id = " + id,
				null);
		while (cursor.moveToNext()) {
			voice_path = cursor.getString(cursor.getColumnIndex("voice_path"));
			voice_note = cursor.getString(cursor.getColumnIndex("voice_note"));
			setVoiceView();
			setVoiceData();
		}
	}

	private void setImageView() {
		initializeImageVariables();
		// 动态添加到linearLayout中之前，必须把View组件重新实例化
		iv_image = new ImageView(ContentEditActivity.this);
		tv_image_note = new TextView(ContentEditActivity.this);
		int count = imageShowMap.size();
		imageId = count + 1;
		// 设置图片ImageView
		imageListLayout = (LinearLayout) findViewById(R.id.llayout_edit_page_image_list);
		Debug.logForLijing("imageListLayout：" + imageListLayout);
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = 4;
		bitmap = BitmapFactory.decodeFile(image_path, opts);
		LinearLayout.LayoutParams ivParams = new LinearLayout.LayoutParams(500,
				500);
		iv_image.setId(imageId);
		iv_image.setLayoutParams(ivParams);
		iv_image.setImageBitmap(bitmap);
		iv_image.setScaleType(ScaleType.FIT_CENTER);
		iv_image.setOnLongClickListener(new OnLongClickListener() {
			int clickViewID;

			@Override
			public boolean onLongClick(View v) {
				// spinner_edit_page_picture_operation
				clickViewID = v.getId();
				builder = new AlertDialog.Builder(ContentEditActivity.this);
				builder.setTitle(R.string.txt_edit_page_title_image_operation);
				dialogitems = getResources().getStringArray(
						R.array.spinner_edit_page_picture_operation);
				builder.setItems(dialogitems,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									// 删除图片
									// imageShowMap不采用remove，因为key的机制是按照size大小来递增的，
									// remove之后，size和key序列就失去了对应关系
									setImageDeleteData(clickViewID);
									imageShowMap.put(clickViewID, null);
									// 更新界面
									imageListLayout.removeAllViews();
									Object[] key_arr = imageShowMap.keySet()
											.toArray();
									Arrays.sort(key_arr);
									for (Object key : key_arr) {
										ArrayList<View> value = imageShowMap
												.get(key);
										if (value != null) {
											imageListLayout.addView(value
													.get(0));
											imageListLayout.addView(value
													.get(1));
										}
									}
									break;
								}
							}
						});
				builder.create().show();

				// 必须返回true，否则报错。
				return true;
			}
		});

		// 设置图片说明TextView
		LayoutParams tvParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		tv_image_note.setLayoutParams(tvParams);
		tv_image_note.setGravity(Gravity.CENTER);
		tv_image_note.setText(image_note);
		ArrayList<View> viewShowList = new ArrayList<View>();
		viewShowList.add(iv_image);
		viewShowList.add(tv_image_note);
		imageShowMap.put(imageId, viewShowList);

		// 更新界面
		imageListLayout.removeAllViews();
		Object[] key_arr = imageShowMap.keySet().toArray();
		Arrays.sort(key_arr);
		for (Object key : key_arr) {
			ArrayList<View> value = imageShowMap.get(key);
			if (value != null) {
				imageListLayout.addView(value.get(0));
				imageListLayout.addView(value.get(1));
			}
		}
	}

	private void setImageData() {
		if (!isNewContext) {
			// 如果不是新增，则是编辑条目，则将图片信息保存在imageDataMap，
			// 编辑时新增或是删除的会存放在imageNewDateMap和imageDeleteDataMap
			imageDataList = new ArrayList<String>();
			imageDataList.add(0, image_path);
			imageDataList.add(1, image_note);
			imageDataMap.put(imageId, imageDataList);
			// 编辑时初始的图片条目数，如果编辑时做了图片删除操作会用到
			imageOriginalCount = imageDataMap.size() + 1;
		}
	}

	private void setImageNewData() {
		// 如果是新增的，那么就将新增的图片信息保存在imageNewDateMap
		imageDataList = new ArrayList<String>();
		imageDataList.add(0, image_path);
		imageDataList.add(1, image_note);
		imageNewDataMap.put(imageId, imageDataList);
	}

	private void setImageDeleteData(int viewID) {
		if (!isNewContext) {
			// 编辑时删除图片，要判断是编辑前原有的图片，还是编辑时新增的图片
			if (viewID <= imageOriginalCount) {
				imageDataList = new ArrayList<String>();
				imageDeleteDataMap.put(viewID, imageDataMap.get(viewID).get(0));
			} else {
				imageNewDataMap.remove(viewID);
			}
		}
	}

	private void setImageNoteDialog() {
		// 弹出对话框，输入照片备注
		builder = new AlertDialog.Builder(ContentEditActivity.this);
		builder.setTitle(R.string.txt_edit_page_title_image_note);
		edt_imageNote = new EditText(ContentEditActivity.this);
		builder.setView(edt_imageNote);
		builder.setPositiveButton(R.string.text_dialog_ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						image_note = edt_imageNote.getText().toString();
						tv_image_note.setText(image_note);
						getWindow()
								.setSoftInputMode(
										WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
						setImageNewData();
					}
				});

		builder.create().show();
	}

	private void setVoiceNoteDialog() {
		// 弹出对话框，输入照片备注
		builder = new AlertDialog.Builder(ContentEditActivity.this);
		builder.setTitle(R.string.txt_edit_page_title_voice_note);
		edt_voiceNote = new EditText(ContentEditActivity.this);
		builder.setView(edt_voiceNote);
		builder.setPositiveButton(R.string.text_dialog_ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						voice_note = edt_voiceNote.getText().toString();
						tv_voice_note.setText(voice_note);
						getWindow()
								.setSoftInputMode(
										WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
						setVoiceNewData();
					}
				});

		builder.create().show();
	}

	private void setVoiceView() {
		initializeVoiceVariables();
		iv_voice = new ImageView(ContentEditActivity.this);
		tv_voice_note = new TextView(ContentEditActivity.this);
		voiceId = voiceShowMap.size() + 1;

		iv_voice.setId(voiceId);
		iv_voice.setImageResource(R.drawable.record);
		iv_voice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String clickVoiceFilePath = "";
				if (isNewContext) {
					clickVoiceFilePath = voiceNewDataMap.get(v.getId()).get(0)
							.toString();
				} else {
					if (v.getId() <= voiceOriginalCount) {
						clickVoiceFilePath = voiceDataMap.get(v.getId()).get(0)
								.toString();
					} else {
						clickVoiceFilePath = voiceDataMap.get(v.getId()).get(0)
								.toString();
					}
				}

				Intent intent = new Intent("android.intent.action.VIEW");
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra("oneshot", 0);
				intent.putExtra("configchange", 0);
				Uri uri = Uri.fromFile(new File(clickVoiceFilePath));
				intent.setDataAndType(uri, "audio/*");
				startActivity(intent);
			}
		});

		tv_voice_note.setText(voice_note);
		voiceListLayoutRow = new TableRow(ContentEditActivity.this);
		voiceListLayoutRow.setGravity(Gravity.CENTER_VERTICAL);
		voiceListLayoutRow.addView(iv_voice);
		voiceListLayoutRow.addView(tv_voice_note);
		voiceShowMap.put(voiceId, voiceListLayoutRow);

		// 更新界面
		voiceListLayout.removeAllViews();
		Object[] key_arr = voiceShowMap.keySet().toArray();
		Arrays.sort(key_arr);
		for (Object key : key_arr) {
			View value = voiceShowMap.get(key);
			if (value != null) {
				voiceListLayout.addView(value);
			}
		}
	}

	private void setVoiceNewData() {
		// 如果是新增的，那么就将新增的录音信息保存在voiceNewDateMap
		voiceDataList = new ArrayList<String>();
		voiceDataList.add(0, voice_path);
		voiceDataList.add(1, voice_note);
		voiceNewDataMap.put(voiceId, voiceDataList);
	}

	private void setVoiceData() {
		if (!isNewContext) {
			// 如果不是新增，则是编辑条目，则将图片信息保存在voiceDataMap，
			// 编辑时新增或是删除的会存放在voiceNewDateMap和voiceDeleteDataMap
			voiceDataList = new ArrayList<String>();
			voiceDataList.add(0, voice_path);
			voiceDataList.add(1, voice_note);
			voiceDataMap.put(voiceId, voiceDataList);
			// 编辑时初始的录音条目数，如果编辑时做了录音删除操作会用到
			voiceOriginalCount = voiceDataMap.size() + 1;
		}
	}

	public int getSpinnerPosition(String currentStr, int array_id) {

		int position = 0;
		String[] array = getResources().getStringArray(array_id);
		for (int i = 0; i < array.length; i++) {
			if (currentStr.equals(array[i])) {
				position = i;
			}
		}
		return position;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ActivityGroup#onStop()
	 */
	@Override
	protected void onDestroy() {

		if (dbHelper != null) {
			dbHelper.close();
		}
		if (db != null) {
			db.close();
		}
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_alert_model, menu);
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {

		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay(); // 为获取屏幕宽、高
		switch (id) {
		case DIALOG_SELECT_PICTURE:
			// 图片选择Dialog
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_choose_picture);
			dialog.setTitle(R.string.context_tab_select_picture_dialog_title);
			LayoutParams layoutParamsForSelectPictureDialog = dialog
					.getWindow().getAttributes();

			// layoutParams.height = (int) (display.getHeight() * 1.0);
			// //高度设置为屏幕的1.0
			layoutParamsForSelectPictureDialog.width = (int) (display
					.getWidth() * 0.7); // 宽度设置为屏幕的0.7
			// layoutParams.alpha = 1.0f; //设置本身透明度
			// layoutParams.dimAmount = 0.0f; //设置黑暗度
			dialog.getWindow()
					.setAttributes(layoutParamsForSelectPictureDialog); // 设置生效

			break;
		case DIALOG_CUSTOM_INCIDENT_CLASS:
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_custom_incident_class);
			dialog.setTitle(R.string.context_tab_custom_incident_class_dialog_title);
			LayoutParams layoutParamsForCustomIncidentClass = dialog
					.getWindow().getAttributes();
			layoutParamsForCustomIncidentClass.width = (int) (display
					.getWidth() * 0.8); // 宽度设置为屏幕的0.8
			dialog.getWindow()
					.setAttributes(layoutParamsForCustomIncidentClass); // 设置生效
			break;
		case DIALOG_CUSTOM_INCIDENT_REPEAT_TYPE:
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_custom_incident_class);
			dialog.setTitle(R.string.context_tab_custom_incident_class_dialog_title);
			LayoutParams layoutParamsForCustomIncidentRepeatType = dialog
					.getWindow().getAttributes();
			layoutParamsForCustomIncidentRepeatType.width = (int) (display
					.getWidth() * 0.8); // 宽度设置为屏幕的0.8
			dialog.getWindow().setAttributes(
					layoutParamsForCustomIncidentRepeatType); // 设置生效

			// 重复频率Spinner代码
			Spinner repeatTypeSpinner = (Spinner) dialog
					.findViewById(R.id.incidentRepeatFrequencySpinner_CustomIncidentRepeatTypeDialog);
			ArrayAdapter<CharSequence> repeatTypeSpinnerAdapter = ArrayAdapter
					.createFromResource(this,
							R.array.spinner_edit_page_remind_frequency,
							android.R.layout.simple_spinner_item);
			repeatTypeSpinnerAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			repeatTypeSpinner.setAdapter(repeatTypeSpinnerAdapter);
			break;
		case DIALOG_REMIND_MODEL_LIST_ACTION:
			dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_remind_mode_list_action);
			dialog.setTitle(R.string.context_tab_custom_incident_class_dialog_title);
			LayoutParams layoutParamsForRemindModelListAction = dialog
					.getWindow().getAttributes();
			layoutParamsForRemindModelListAction.width = (int) (display
					.getWidth() * 0.6); // 宽度设置为屏幕的0.6
			dialog.getWindow().setAttributes(
					layoutParamsForRemindModelListAction); // 设置生效

			Button editRemindModelButton = (Button) dialog
					.findViewById(R.id.button_dailog_remind_model_list_action_edit);
			Button deleteRemindModelButton = (Button) dialog
					.findViewById(R.id.button_dailog_remind_model_list_action_delete);

			editRemindModelButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(ContentEditActivity.this,
							AlertEditActivity.class);
					intent.putExtras(bundleForDialog);
					intent.putExtra("action",
							INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_EDIT_ACTION);
					startActivityForResult(intent,
							INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_EDIT_ACTION);
					dialog.dismiss();
				}
			});

			deleteRemindModelButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					AlertDialog.Builder builder = new AlertDialog.Builder(
							ContentEditActivity.this);

					builder.setTitle(R.string.dialog_remind_model_list_delete_action_countersign_title);
					builder.setIcon(android.R.drawable.ic_dialog_info);

					builder.setPositiveButton(
							R.string.dialog_remind_model_list_delete_action_countersign_button_ok_text,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									int id = Integer.parseInt(bundleForDialog
											.getString("id"));
									DatabaseHelper databaseHelper = DatabaseHelper
											.getDBhelper(ContentEditActivity.this);
									SQLiteDatabase db = databaseHelper
											.getReadableDatabase();

									db.execSQL("update context set mode='0' where mode="
											+ id);

									db.execSQL("delete from remind_mode where id="
											+ id);

									db.close();
									databaseHelper.close();

									alertModelListViewArrayAdapter.refresh();

									alertDialog.dismiss();
								}
							});

					builder.setNegativeButton(
							R.string.dialog_remind_model_list_delete_action_countersign_button_cancel_text,

							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					alertDialog = builder.create();
					alertDialog.show();
					dialog.dismiss();
				}
			});

			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	/*
	 * 根据ListView adapter中的item数量自动计算ListView高度，并自动调整
	 */
	// public static void reSetListViewHeight(ListView listView) {
	// ListAdapter listAdapter = listView.getAdapter();
	// if (listAdapter == null) {
	// return;
	// }
	//
	// int totalHeight = 0;
	// for (int i = 0; i < listAdapter.getCount(); i++) {
	// View listItem = listAdapter.getView(i, null, listView);
	// listItem.measure(0, 0);
	// totalHeight += listItem.getMeasuredHeight();
	// }
	//
	// ViewGroup.LayoutParams params = listView.getLayoutParams();
	// params.height = totalHeight
	// + (listView.getDividerHeight() * (listAdapter.getCount() - 1))
	// + listView.getPaddingTop() + listView.getPaddingBottom();
	// listView.setLayoutParams(params);
	// }

	class DateTimeBtnListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			final Builder builder = new AlertDialog.Builder(
					ContentEditActivity.this);
			TableLayout pickerDateTime = (TableLayout) getLayoutInflater()
					.inflate(R.layout.picker_datetime, null);
			builder.setTitle("设置开始时间");

			// 上面一段分解开来即如下代码
			// LayoutInflater inflater = getLayoutInflater();
			// View view = inflater.inflate(R.layout.delaynote, null);
			// TableLayout delayNote = (TableLayout)view;
			builder.setView(pickerDateTime);

			// 获得出线在对话框中的DatePicker和TimePicker
			DatePicker datePicker = (DatePicker) pickerDateTime
					.findViewById(R.id.datePicker);
			TimePicker timePicker = (TimePicker) pickerDateTime
					.findViewById(R.id.timePicker);
			if (startDate == null) {
				Calendar c = Calendar.getInstance();
				year = c.get(Calendar.YEAR);
				month = c.get(Calendar.MONTH);
				day = c.get(Calendar.DAY_OF_MONTH);
				hour = c.get(Calendar.HOUR_OF_DAY);
				minute = c.get(Calendar.MINUTE);
			} else {
				year = Integer.parseInt(new SimpleDateFormat("yyyy")
						.format(startDate));
				month = startDate.getMonth();
				day = startDate.getDate();
				hour = startDate.getHours();
				minute = startDate.getMinutes();
			}

			datePicker.init(year, month, day, new OnDateChangedListener() {

				@Override
				public void onDateChanged(DatePicker view, int newyear,
						int newmonth, int newday) {
					year = newyear;
					month = newmonth;
					day = newday;
				}
			});
			timePicker.setCurrentHour(hour);
			timePicker.setCurrentMinute(minute);
			timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
				@Override
				public void onTimeChanged(TimePicker view, int newhour,
						int newminute) {
					hour = newhour;
					minute = newminute;
				}
			});

			// 为对话框设置"确定"按钮
			// 注意，为了跟View中的button的事件却分，需要在OnClickListener前面加上DialogInterface
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startDate = new Date(year - 1900, month, day, hour,
									minute);
							buttonStartDate.setText(new SimpleDateFormat(
									"yyyy-MM-dd HH:mm").format(startDate));
							Toast.makeText(
									ContentEditActivity.this,
									"日期时间设置为：："
											+ new SimpleDateFormat(
													"yyyy-MM-dd HH:mm")
													.format(startDate),
									Toast.LENGTH_SHORT).show();
						}
					});
			// 为对话框设置"确定"按钮
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			// 启动builder
			builder.create().show();

		}
	}

	class SaveButtonOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			String title = (String) edtTitle.getText().toString();
			String summary = (String) edtSummary.getText().toString();
			String level = null;
			long start_date = 0;
			String repeat_type = null;
			String class_type = null;
			int selectedLevel = spinnerLevel.getSelectedItemPosition();
			level = (String) spinnerLevel.getSelectedItem();
			int selectedRepeatType = spinnerRepeatType
					.getSelectedItemPosition();
			repeat_type = (String) spinnerRepeatType.getSelectedItem();
			int selectedClass = spinnerClass.getSelectedItemPosition();
			class_type = (String) spinnerClass.getSelectedItem();
			if (startDate == null) {
				start_date = (new Date()).getTime();
			} else {
				start_date = startDate.getTime();
			}

			Log.d("sunway", "alertModelListView.getCheckedItemPosition():"
					+ alertModelListView.getCheckedItemPosition());

			int selectedAlertModel = 0;

			int checkedItemPosition = alertModelListView
					.getCheckedItemPosition();

			if (alertModelListView.getCheckedItemPosition() != -1) {
				selectedAlertModel = ((AlertModelBean) alertModelListViewArrayAdapter
						.getItem(alertModelListView.getCheckedItemPosition()))
						.getId();
			}

			int selectedShareToUsers = shareToSpinner.getSelectedItemPosition();
			if (checkBoxShareToGroup.isChecked()) {
				// Log.d("lijing", "选择了组");
			} else {
				// Log.d("lijing", "未选择组");
			}
			// Log.d("lijing", "分享给：" + selectedShareToUsers
			// + (String) shareToSpinner.getSelectedItem());
			if (checkBoxShareTask.isChecked()) {
				// Log.d("lijing", "共享方式：" + checkBoxShareTask.getText());
			}
			if (checkBoxShareBySMS.isChecked()) {
				// Log.d("lijing", "共享方式：" + checkBoxShareBySMS.getText());
			}
			if (checkBoxShareByEmail.isChecked()) {
				// Log.d("lijing", "共享方式：" + checkBoxShareByEmail.getText());
			}

			if (isNewContext) {
				// 如果context_id不存在，则说明是新增条目
				db.execSQL("insert into context(id,user_id,title,summary,level,start_date,repeat,class,mode) "
						+ "values("
						+ context_id
						+ ",'"
						+ "lijing"
						+ "','"
						+ title
						+ "','"
						+ summary
						+ "','"
						+ level
						+ "','"
						+ start_date
						+ "','"
						+ repeat_type
						+ "','"
						+ class_type
						+ "','" + selectedAlertModel + "')");

				// 保存图片到数据库
				if (imageNewDataMap != null && !imageNewDataMap.isEmpty()) {
					Iterator<?> iterator = imageNewDataMap.entrySet()
							.iterator();
					while (iterator.hasNext()) {
						@SuppressWarnings("unchecked")
						Entry<Integer, ArrayList<String>> entry = (Entry<Integer, ArrayList<String>>) iterator
								.next();
						ArrayList<String> val = (ArrayList<String>) entry
								.getValue();
						String image_path = val.get(0);
						String image_note = val.get(1);
						Log.d("lijing", "插入图片数据" + image_path + "|"
								+ image_note + "|" + context_id);
						db.execSQL("insert into image(image_path,image_note,context_id) values('"
								+ image_path
								+ "','"
								+ image_note
								+ "',"
								+ context_id + ")");
					}
					// 验证查询入库数据
					// cursor = db.rawQuery(
					// "select * from image where context_id="
					// + context_id, null);
					// while (cursor.moveToNext()) {
					// Log.d("lijing",
					// "验证查询入库数据："
					// + cursor.getString(cursor
					// .getColumnIndex("image_path"))
					// + "|"
					// + cursor.getString(cursor
					// .getColumnIndex("image_note"))
					// + "|"
					// + cursor.getString(cursor
					// .getColumnIndex("context_id"))
					// + "|");
					// }
				}

				// 保存录音到数据库
				if (voiceNewDataMap != null && !voiceNewDataMap.isEmpty()) {
					Iterator<?> iterator = voiceNewDataMap.entrySet()
							.iterator();
					while (iterator.hasNext()) {

						@SuppressWarnings("unchecked")
						Entry<Integer, ArrayList<String>> entry = (Entry<Integer, ArrayList<String>>) iterator
								.next();
						ArrayList<String> val = (ArrayList<String>) entry
								.getValue();
						String voice_path_value = val.get(0);
						String voice_note_value = val.get(1);
						Log.d("lijing", "插入录音数据" + voice_path_value + "|"
								+ voice_note_value + "|" + context_id);
						db.execSQL("insert into voice(voice_path,voice_note,context_id) values('"
								+ voice_path_value
								+ "','"
								+ voice_note_value
								+ "'," + context_id + ")");
					}

				}
			} else {
				// 如果context_id存在，则说明是修改条目
				db.execSQL("update context set " + "title='" + title + "',"
						+ "summary='" + summary + "'," + "level='" + level
						+ "'," + "start_date='" + start_date + "',"
						+ "end_date='结束时间'," + "repeat='" + repeat_type + "',"
						+ "class='" + class_type + "'," + "mode='"
						+ selectedAlertModel + "' where id=" + context_id);

				// 删除在界面上去掉的图片
				if (imageDeleteDataMap != null && !imageDeleteDataMap.isEmpty()) {
					Iterator<?> iterator = imageDeleteDataMap.entrySet()
							.iterator();
					while (iterator.hasNext()) {
						@SuppressWarnings("unchecked")
						Entry<Integer, String> entry = (Entry<Integer, String>) iterator
								.next();
						String delete_image_path = (String) entry.getValue();
						Debug.logForLijing("删除图片数据" + delete_image_path + "|"
								+ context_id);
						db.execSQL("delete from image where image_path='"
								+ delete_image_path + "'");
					}

					// 验证删除后的数据
					// cursor = db.rawQuery(
					// "select * from image where context_id="
					// + context_id, null);
					// while (cursor.moveToNext()) {
					// Log.d("lijing",
					// "验证删除后的数据："
					// + cursor.getString(cursor
					// .getColumnIndex("image_path"))
					// + "|"
					// + cursor.getString(cursor
					// .getColumnIndex("image_note"))
					// + "|"
					// + cursor.getString(cursor
					// .getColumnIndex("context_id"))
					// + "|");
					// }
				}

				// 保存新添加的图片到数据库
				if (imageNewDataMap != null && !imageNewDataMap.isEmpty()) {
					Iterator<?> iterator = imageNewDataMap.entrySet()
							.iterator();
					while (iterator.hasNext()) {
						@SuppressWarnings("unchecked")
						Entry<Integer, ArrayList<String>> entry = (Entry<Integer, ArrayList<String>>) iterator
								.next();
						ArrayList<String> val = (ArrayList<String>) entry
								.getValue();
						String image_path = val.get(0);
						String image_note = val.get(1);
						Log.d("lijing", "插入新添加的图片数据" + image_path + "|"
								+ image_note + "|" + context_id);
						db.execSQL("insert into image(image_path,image_note,context_id) values('"
								+ image_path
								+ "','"
								+ image_note
								+ "',"
								+ context_id + ")");
					}
					cursor = db.rawQuery(
							"select * from image where context_id="
									+ context_id, null);
					while (cursor.moveToNext()) {
						Log.d("lijing",
								"验证查询新添加的入库数据："
										+ cursor.getString(cursor
												.getColumnIndex("image_path"))
										+ "|"
										+ cursor.getString(cursor
												.getColumnIndex("image_note"))
										+ "|"
										+ cursor.getString(cursor
												.getColumnIndex("context_id"))
										+ "|");
					}
				}

				// 删除录音
				if (voiceDeleteDataMap != null && !voiceDeleteDataMap.isEmpty()) {
					Iterator<?> iterator = voiceNewDataMap.entrySet()
							.iterator();
					while (iterator.hasNext()) {
						@SuppressWarnings("unchecked")
						Entry<Integer, ArrayList<String>> entry = (Entry<Integer, ArrayList<String>>) iterator
								.next();
						ArrayList<String> val = (ArrayList<String>) entry
								.getValue();
						String voice_path_value = val.get(0);
						String voice_note_value = val.get(1);
						Log.d("lijing", "删除录音数据" + voice_path_value + "|"
								+ voice_note_value + "|" + context_id);
						db.execSQL("delete from voice where voice_path='"
								+ voice_path_value + "'");
					}
				}
				// 新增录音
				if (voiceNewDataMap != null && !voiceNewDataMap.isEmpty()) {
					Iterator<?> iterator = voiceNewDataMap.entrySet()
							.iterator();
					while (iterator.hasNext()) {

						@SuppressWarnings("unchecked")
						Entry<Integer, ArrayList<String>> entry = (Entry<Integer, ArrayList<String>>) iterator
								.next();
						ArrayList<String> val = (ArrayList<String>) entry
								.getValue();
						String voice_path_value = val.get(0);
						String voice_note_value = val.get(1);
						Log.d("lijing", "插入录音数据" + voice_path_value + "|"
								+ voice_note_value + "|" + context_id);
						db.execSQL("insert into voice(voice_path,voice_note,context_id) values('"
								+ voice_path_value
								+ "','"
								+ voice_note_value
								+ "'," + context_id + ")");
					}
				}

			}
			onDestroy();
			finish();
		}
	}

	class CancleButtonOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(ContentEditActivity.this, IndexActivity.class);
			startActivity(intent);
		}
	}

	class CameraButtonClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			builder = new AlertDialog.Builder(ContentEditActivity.this);
			builder.setTitle(R.string.txt_edit_page_title_select_image);
			dialogitems = getResources().getStringArray(
					R.array.spinner_edit_page_picture_select);
			builder.setItems(dialogitems,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case 0:
								// 拍照获取
								Log.d("lijing", "点击了拍照获取选项");
								initializeImageVariables();
								Intent intent = new Intent();
								intent.setClass(ContentEditActivity.this,
										CameraActivity.class);
								intent.putExtra("image_dir_path",
										imageFileDirPath);
								lastImageFileName = (new Date()).getTime()
										+ ".jpg";
								image_path = imageFileDirPath
										+ lastImageFileName;
								intent.putExtra("image_filename",
										lastImageFileName);
								startActivityForResult(intent,
										INTENT_REQUEST_CODE_FOR_START_CAMERA_ACTRIVTY);
								break;
							case 1:
								// 本地图片
								break;
							}
						}
					});
			builder.create().show();
		}
	}

	private Message msg;
	private long startTime;
	final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			String time;
			super.handleMessage(msg);
			time = new SimpleDateFormat("HH:mm:ss").format(new Date(new Date()
					.getTime()
					- startTime
					- TimeZone.getDefault().getRawOffset()));
			tv_record_time.setText(time);
			Debug.logForLijing("录制时间：" + time);
		}
	};

	private class SetRecordTimeThread extends Thread {

		final static int STATE_DONE = 0;
		final static int STATE_RUNNING = 1;
		int currentState;

		@Override
		public void run() {
			currentState = STATE_RUNNING;
			startTime = new Date().getTime();
			while (currentState == STATE_RUNNING) {
				Debug.logForLijing("STATE_RUNNING:更新时间");
				handler.sendMessage(new Message());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		public void setState(int setState) {
			currentState = setState;
		}
	}

	// 录音按钮监听器
	class VoiceButtonClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_edit_page_add_voice: {
				lastVoiceFilesName = (new Date()).getTime() + ".amr";
				voice_path = voiceDirPath + lastVoiceFilesName;

				// 初始化录音Dialog中的Layout元素
				voiceDialogView = (LinearLayout) getLayoutInflater().inflate(
						R.layout.dialog_record_voice, null);
				btn_play_pause = (Button) voiceDialogView
						.findViewById(R.id.btn_edit_page_play_voice);
				btn_record = (Button) voiceDialogView
						.findViewById(R.id.btn_edit_page_record_voice);
				psb_record = (ProgressBar) voiceDialogView
						.findViewById(R.id.psb_edit_page_record_process);
				tv_record_time = (TextView) voiceDialogView
						.findViewById(R.id.txt_edit_page_record_time);
				btn_record.setOnClickListener(new VoiceButtonClickListener());
				btn_play_pause
						.setOnClickListener(new VoiceButtonClickListener());

				builder = new AlertDialog.Builder(ContentEditActivity.this);
				builder.setTitle(R.string.txt_edit_page_record_dialog_title);
				builder.setView(voiceDialogView);
				builder.setPositiveButton(R.string.text_dialog_ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// 确认录音完毕
								if (isRecordButtonPressed) {
									isRecordButtonPressed = false;
									btn_record
											.setBackgroundDrawable(getResources()
													.getDrawable(
															R.drawable.record));
									if (soundFile != null && soundFile.exists()) {
										// 停止录音
										mRecorder.stop();
										// 释放资源
										mRecorder.release();
										mRecorder = null;
									}
								}
								recordTimeThread
										.setState(SetRecordTimeThread.STATE_DONE);
								setVoiceView();
								setVoiceNoteDialog();
							}
						});
				builder.setNegativeButton(R.string.text_dialog_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						});
				builder.create().show();
				isFirstTimeOfAddVoice = false;
				break;
			}
			case R.id.btn_edit_page_play_voice: {
				if (!isPlayButtonPressed) {
					isPlayButtonPressed = !isPlayButtonPressed;
					btn_play_pause
							.setBackgroundResource(R.drawable.playandpause_pressed);
					psb_record.setVisibility(View.VISIBLE);
					mPlayer = new MediaPlayer();
					try {
						mPlayer.setDataSource(voice_path);
						mPlayer.prepare();
						mPlayer.start();
						recordTimeThread = new SetRecordTimeThread();
						recordTimeThread.start();
						mPlayer.setOnCompletionListener(new OnCompletionListener() {
							@Override
							public void onCompletion(MediaPlayer mp) {
								mPlayer.release();
								isPlayButtonPressed = !isPlayButtonPressed;
								btn_play_pause
										.setBackgroundResource(R.drawable.playandpause);
								psb_record.setVisibility(View.INVISIBLE);
								recordTimeThread
										.setState(SetRecordTimeThread.STATE_DONE);
								tv_record_time
										.setText(R.string.txt_edit_page_record_starttime);
							}
						});
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					isPlayButtonPressed = !isPlayButtonPressed;
					btn_play_pause
							.setBackgroundResource(R.drawable.playandpause);
					psb_record.setVisibility(View.INVISIBLE);
					mPlayer.release();
					recordTimeThread.setState(SetRecordTimeThread.STATE_DONE);
					tv_record_time
							.setText(R.string.txt_edit_page_record_starttime);
				}

				break;
			}
			case R.id.btn_edit_page_record_voice: {
				Debug.logForLijing("点击了录音按钮");
				if (!isRecordButtonPressed) {
					psb_record.setVisibility(View.VISIBLE);
					isRecordButtonPressed = !isRecordButtonPressed;
					btn_record.setBackgroundResource(R.drawable.record_pressed);
					if (!Environment.getExternalStorageState().equals(
							android.os.Environment.MEDIA_MOUNTED)) {
						Toast.makeText(ContentEditActivity.this,
								"SD卡不存在，请插入SD卡！", 5000).show();
						return;
					}
					Debug.logForLijing(voiceDirPath);
					File dirPath = new File(voiceDirPath);
					if (!dirPath.exists()) {
						dirPath.mkdirs();
					}
					try {
						// 创建保存录音的音频文件
						soundFile = new File(voice_path);
						mRecorder = new MediaRecorder();
						// 设置录音的声音来源
						mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
						// 设置录制的声音的输出格式（必须在设置声音编码格式之前设置）
						mRecorder
								.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
						// 设置声音编码的格式
						mRecorder
								.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
						mRecorder.setOutputFile(soundFile.getAbsolutePath());
						mRecorder.prepare();
						// 开始录音
						tv_record_time
								.setText(R.string.txt_edit_page_record_starttime);
						mRecorder.start();
						// 启动一个线程，更新录音时间。

						recordTimeThread = new SetRecordTimeThread();
						recordTimeThread.start();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					psb_record.setVisibility(View.INVISIBLE);
					isRecordButtonPressed = !isRecordButtonPressed;
					btn_record.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.record));
					if (soundFile != null && soundFile.exists()) {
						// 停止录音
						mRecorder.stop();
						// 释放资源
						mRecorder.release();
						mRecorder = null;
					}
					recordTimeThread.setState(SetRecordTimeThread.STATE_DONE);
				}
				break;
			}
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case INTENT_REQUEST_CODE_FOR_START_CAMERA_ACTRIVTY: {
			if (resultCode == 0) {
				setImageView();
				setImageNoteDialog();
			}
			break;
		}
		case INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_CREATE_ACTION: {
			if (resultCode == 1) {
				alertModelListViewArrayAdapter.refresh();
			}
		}
		case INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_EDIT_ACTION: {
			if (resultCode == 1) {
				alertModelListViewArrayAdapter.refresh();
			}
		}
		}
	}
}
